package com.dcits.ftz.auth;

import com.dcits.common.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.util.AntPathMatcher;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    private final JwtUtil jwtUtil;
    private final JwtConfig jwtConfig;

    public JwtFilter(JwtUtil jwtUtil, JwtConfig jwtConfig) {
        this.jwtUtil = jwtUtil;
        this.jwtConfig = jwtConfig;
    }

    /**
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)) {
            try {
                return executeLogin(request, response);
            } catch (Exception e) {
                responseError(response, e.getMessage());
                return false;
            }
        }
        // 2. 如果是anon放行的请求，直接返回true
        if (isAnonRequest(request)) {
            return true;
        }
        responseError(response, "需要认证");

        return false;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        return token != null && token.startsWith("Bearer ");
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authHeader = httpServletRequest.getHeader("Authorization");

        // 提取实际的Token（去掉Bearer前缀）
        String token = authHeader.substring(7);

        // 校验Token有效性
        if (!jwtUtil.validateToken(token)) {
            throw new AuthenticationException("无效的token");
        }

        // 检查Token是否过期
        if (jwtUtil.isTokenExpired(token)) {
            throw new AuthenticationException("Token已过期");
        }

        // 创建Shiro Token
        JwtToken jwtToken = new JwtToken(token);

        // 提交给Realm进行登录
        getSubject(request, response).login(jwtToken);

        return true;
    }

    /**
     * 响应异常结果
     *
     * @param response
     * @param message
     */
    private void responseError(ServletResponse response, String message) {
        try {
            // 完全禁用WWW-Authenticate头，防止浏览器弹窗
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setContentType("application/json;charset=utf-8");
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.getWriter().write(new ObjectMapper().writeValueAsString(Result.fail("401000", message)));
        } catch (IOException e) {
            log.error("响应结果异常", e);
        }
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        // 处理跨域
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));

        // 放行OPTIONS请求
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }

    private boolean isAnonRequest(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();

        // 这里应该与ShiroConfig中anon配置的路径一致
        final String[] ingoreUris = jwtConfig.getIngoreUri().split("\\s*,\\s*");
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String ingoreUri : ingoreUris) {
            if (pathMatcher.match(ingoreUri, uri)) {
                return true;
            }
        }
        return false;
    }
}